﻿namespace MagicWatering.UI
{
    using System.IO;
    using System.Reflection;
    using System.Windows.Forms;

    using MagicWatering.Scheduler.Engine;

    public partial class MainControlPanel : Form
    {
        #region Instance fields

        private readonly WateringManager s_Manager;
        private bool m_isRun;

        #endregion

        #region Constructors and Finalizers

        public MainControlPanel()
        {
            InitializeComponent();

            this.Closed += MainControlPanelClosed;
            s_Manager = new WateringManager(
                new FeedbackService(this),
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Adam6060Controller");

            m_isRun = false;
            m_timePicker.Value = s_Manager.Plan.ExecutionTime;
        }

        void MainControlPanelClosed(object sender, System.EventArgs e)
        {
            s_Manager.Plan.ExecutionTime = m_timePicker.Value;
            s_Manager.SavePlan();
        }

        #endregion

        #region Delegates

        private delegate void ObjectDelegate(string message);

        #endregion

        #region Public Methods

        public void AddMessage(string message)
        {
            if (listBoxOutput.InvokeRequired)
            {
                ObjectDelegate method = AddMessage;
                Invoke(
                    method,
                    new object[]
                    {
                        message
                    });
            }
            else
            {
                listBoxOutput.Items.Add(message);
            }
        }

        #endregion

        #region Methods

        #endregion

        private void OnCheckBoxCheckedChanged(object sender, System.EventArgs e)
        {
            if (m_isRun == m_startStopCheckBox.Checked)
            {
                return;
            }
            m_isRun = m_startStopCheckBox.Checked;

            if (m_isRun)
            {
                s_Manager.Plan.ExecutionTime = m_timePicker.Value;
                s_Manager.Start();
                m_timePicker.Enabled = false;
            }
            else
            {
                s_Manager.Stop();
                m_timePicker.Enabled = true;
            }
        }
    }
}